import { HttpException, HttpStatus, Injectable, UseFilters } from "@nestjs/common";
import * as md5 from "md5";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";

import { User, UserDocument } from "./schemas/user.schema";
// 使用 class-validator 校验账号信息 这里只是类型
import type { ValidateAccountDto, ValidatePasswordDto } from "./dto/validate-account.dto";
// import validateAccount from "./common/validate-account"; // 函数校验账号信息
import { jwtHelper } from "src/utils";

@Injectable()
export class LoginService {
  constructor(@InjectModel("User") private userModel: Model<UserDocument>) {}
  // * 注册
  async register({ nickname, password }: ValidateAccountDto) {
    // await validateAccount({ nickname, password });
    const result = await this.userModel.findOne({ nickname });
    if (result) {
      throw new HttpException("已有此账号", HttpStatus.BAD_REQUEST);
    } else {
      this.userModel.create({ nickname, password: md5(password) });
      return {};
    }
  }
  // * 登录
  async login({ nickname, password }: ValidateAccountDto) {
    // await validateAccount({ nickname, password });
    const result = await this.userModel.findOne({ nickname });
    if (result) {
      if (md5(password) === result.password) {
        const token = jwtHelper().getToken({ nickname, password });
        return { token, id: result.id };
      } else {
        throw new HttpException("密码错误", HttpStatus.BAD_REQUEST);
      }
    } else {
      throw new HttpException("当前无此账号", HttpStatus.NOT_FOUND);
    }
  }
  // * 更新密码
  async updatePassword({ nickname, newPassword, oldPassword }: ValidatePasswordDto) {
    const result = await this.userModel.findOne({ nickname });
    if (result) {
      if (md5(oldPassword) !== result.password) {
        throw new HttpException("旧密码错误", HttpStatus.BAD_REQUEST);
      }
      if (newPassword === oldPassword) {
        throw new HttpException("新密码不能与旧密码一致", HttpStatus.BAD_REQUEST);
      }
      await this.userModel.updateOne({ id: result.id }, { $set: { password: md5(newPassword) } });
      return {};
    } else {
      throw new HttpException("当前无此账号", HttpStatus.NOT_FOUND);
    }
  }

  remove(id: number) {
    return `This action removes a #${id} login`;
  }
}
